﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Aspose.Cells;
using CRM.UTIL;
using CRM.BLL.Ali;

namespace CRM.WEB.CommonClass
{
    public class Common
    {
        public static string GetNewFileName(string dirPath, string fileName)
        {
            var newFileName = string.Empty;
            var strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);
            if (File.Exists(dirPath + fileName))
            {
                newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) + "(1)." + strFileExt;
                newFileName = GetNewFileName(dirPath, newFileName);
            }
            else
            {
                newFileName = fileName;
            }
            return newFileName;
        }
        public static string GetUpLoadDirPath(HttpServerUtility server, out string folder)
        {
            folder = "/UploadFile/File/";
            string dirPath = server.MapPath(folder);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            //String ymd = DateTime.Now.ToString("yyyy", DateTimeFormatInfo.InvariantInfo);
            dirPath += DateTime.Now.ToString("yyyy", DateTimeFormatInfo.InvariantInfo) + "/";
            folder += DateTime.Now.ToString("yyyy", DateTimeFormatInfo.InvariantInfo) + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            dirPath += DateTime.Now.ToString("MM", DateTimeFormatInfo.InvariantInfo) + "/";
            folder += DateTime.Now.ToString("MM", DateTimeFormatInfo.InvariantInfo) + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            dirPath += DateTime.Now.ToString("dd", DateTimeFormatInfo.InvariantInfo) + "/";
            folder += DateTime.Now.ToString("dd", DateTimeFormatInfo.InvariantInfo) + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            return dirPath;
        }


        /// <summary>
        /// 同步生效数据
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="ids">返回ids</param>
        /// <param name="errorStr">返回error</param>
        /// <param name="resAddSuccessCount">返回新增成功数量</param>
        /// <param name="resAddFaildCount">返回新增失败数量</param>
        /// <param name="resUpdateSuccessCount">返回修改成功数量</param>
        /// <param name="resUpdateFaildCount">返回修改失败数量</param>
        /// <param name="total">返回该时间段内总数量</param>
        /// <param name="syncData">是否同步订单数据</param>
        /// <returns></returns>
        public static bool GetTakeEffectData(string supplierId, DateTime startDate, DateTime endDate, ref string ids, ref string errorStr, out int resAddSuccessCount, out int resAddFaildCount, out int resUpdateSuccessCount, out int resUpdateFaildCount,out int total,bool syncData=false)
        {
            resAddSuccessCount = resAddFaildCount = resUpdateSuccessCount = resUpdateFaildCount = total = 0;

            var resJson = new RunAliAPI().GetEffOrder(startDate.ToString("yyyy-MM-dd") + " 00:00:00",
                endDate.ToString("yyyy-MM-dd") + " 00:00:00", 200, 1, false, false);

            var htFirst = JSON.Decode(resJson) as Hashtable;

            //bool effDateFlag = startDate.AddDays(1) == endDate;
            bool effDateFlag = true;

            var sb = new StringBuilder();
            var errorSb = new StringBuilder();

            if (htFirst["success"].ToString().ToLower() == "true")
            {
                total = int.Parse(htFirst["totalItem"].ToString());

                var arrayList = htFirst["dataList"] as ArrayList;
                if (arrayList != null)
                {
                    // 取出总数，处理第一页
                    foreach (
                        Hashtable item in
                            arrayList.Cast<Hashtable>())
                    {
                        try
                        {
                            var effDate = DateTime.Parse(item["startTime"].ToString());
                            if (item["orderId"] != null && !string.IsNullOrEmpty(item["orderId"].ToString()))
                            {
                                // 更新 为已生效、生效时间
                                if (syncData)
                                {
                                    int asCount, afCount, usCount, ufCount;
                                    var res = SyncAliData(item["orderId"].ToString(), supplierId, out asCount,
                                        out afCount,
                                        out usCount, out ufCount, false, true, effDate,
                                        item["bizId"].ToString());

                                    if (!string.IsNullOrEmpty(res))
                                    {
                                        errorSb.Append(res);
                                    }
                                    resAddSuccessCount += asCount;
                                    resAddFaildCount += afCount;
                                    resUpdateSuccessCount += usCount;
                                    resUpdateFaildCount += ufCount;
                                }

                                sb.AppendFormat(",{0}", item["orderId"]);
                            }
                        }
                        catch (Exception ex)
                        {
                            errorSb.AppendFormat("orderId:{0},bizId:{1} 出错：{2}", item["orderId"], item["bizId"],
                                ex.Message);
                        }
                    }
                }
                for (int i = 2; i <= (total / 200 + 1); i++)
                {
                    int asCount, afCount, usCount, ufCount;
                    AppendOrderID(startDate.ToString("yyyy-MM-dd") + " 00:00:00",
                        endDate.ToString("yyyy-MM-dd") + " 00:00:00", supplierId, i, ref sb, ref errorSb, out asCount,
                        out afCount,
                        out usCount, out ufCount, syncData);

                    resAddSuccessCount += asCount;
                    resAddFaildCount += afCount;
                    resUpdateSuccessCount += usCount;
                    resUpdateFaildCount += ufCount;
                }

                ids = sb.ToString().Trim(',');
                errorStr = errorSb.ToString();
                return true;
            }
            return false;
        }
        /// <summary>
        /// 把订单ID添加进来
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="supplierId"></param>
        /// <param name="pageNo"></param>
        /// <param name="ids"></param>
        /// <param name="errorSb"></param>
        /// <param name="resAddSuccessCount"></param>
        /// <param name="resAddFaildCount"></param>
        /// <param name="resUpdateSuccessCount"></param>
        /// <param name="resUpdateFaildCount"></param>
        /// <param name="syncData">是否同步订单数据</param>
        private static void AppendOrderID(string startDate, string endDate, string supplierId, int pageNo, ref StringBuilder ids, ref StringBuilder errorSb, out int resAddSuccessCount, out int resAddFaildCount, out int resUpdateSuccessCount, out int resUpdateFaildCount, bool syncData=false)
        {
            resAddSuccessCount = resAddFaildCount = resUpdateSuccessCount = resUpdateFaildCount = 0;

            var sb = new StringBuilder();
            var resJson = new RunAliAPI().GetEffOrder(startDate,
                endDate, 200, pageNo, false, false);

            var htFirst = JSON.Decode(resJson) as Hashtable;

            //bool effDateFlag = Convert.ToDateTime(startDate).AddDays(1) == Convert.ToDateTime(endDate);
            bool effDateFlag = true;

            if (htFirst["success"].ToString().ToLower() == "true")
            {
                var arrayList = htFirst["dataList"] as ArrayList;
                if (arrayList != null)
                {
                    foreach (
                        Hashtable item in
                            arrayList.Cast<Hashtable>())
                    {
                        var effDate = DateTime.Parse(item["startTime"].ToString());
                        if (item["orderId"] != null && !string.IsNullOrEmpty(item["orderId"].ToString()))
                        {
                            if (syncData)
                            {
                                int asCount, afCount, usCount, ufCount;
                                var res = SyncAliData(item["orderId"].ToString(), supplierId, out asCount, out afCount,
                                    out usCount, out ufCount, false, true, effDate, item["bizId"].ToString());//Convert.ToDateTime(startDate)

                                if (!string.IsNullOrEmpty(res))
                                {
                                    errorSb.Append(res);
                                }
                                resAddSuccessCount += asCount;
                                resAddFaildCount += afCount;
                                resUpdateSuccessCount += usCount;
                                resUpdateFaildCount += ufCount;

                                sb.AppendFormat(",{0}", item["orderId"]);

                                if (!string.IsNullOrEmpty(res))
                                {
                                    errorSb.Append(res);
                                }
                            }

                            ids.AppendFormat(",{0}", item["orderId"]);
                        }
                    }
                }
            }
            else
            {
                errorSb.AppendFormat("调用阿里接口失败，startDate:{0},endDate:{1},pageNo:{2},msg:{3}", startDate, endDate, pageNo,
                    htFirst["msg"]);
            }
        }

        /// <summary>
        /// 同步订单数据，部分同步还是同步全部， 跟进BizId和OrderID更新生效时间和生效状态
        /// 
        /// 
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="supplierId"></param>
        /// <param name="addSuccessCount"></param>
        /// <param name="addFaildCount"></param>
        /// <param name="updateSuccessCount"></param>
        /// <param name="updateFaildCount"></param>
        /// <param name="syncData"></param>
        /// <param name="effDateFlag"></param>
        /// <param name="effectiveDate"></param>
        /// <param name="bizId"></param>
        /// <returns></returns>
        public static string SyncAliData(string orderID, string supplierId, out int addSuccessCount, out int addFaildCount, out int updateSuccessCount, out int updateFaildCount, bool syncData = false,bool effDateFlag=false, DateTime? effectiveDate=null,string bizId="")
        {
            addSuccessCount = addFaildCount = updateSuccessCount = updateFaildCount = 0;
            var sb = new StringBuilder();

            //根据订单号判断是否存在
            var serv = new Ali_OrdersB();
            var aliApiServ = new RunAliAPI();
            var stu = new MODEL.Ali.GetAli_Orders
            {
                ORDERIDVALUE = orderID,
                BizIDVALUE = bizId
            };

            var oDt = serv.GetAli_Orders(ref stu);

            if (oDt == null || oDt.Rows.Count <= 0)
            {
                #region TODO


                var resJson = aliApiServ.GetOrderInfo(orderID, false, false);
                
                var htFirst = JSON.Decode(resJson) as Hashtable;
                if (htFirst["success"].ToString().ToLower() == "true")
                {
                    var arrayList = htFirst["dataList"] as ArrayList;
                    if (arrayList != null)
                    {
                        var ht = new Hashtable();

                        foreach (Hashtable item in arrayList.Cast<Hashtable>())
                        {
                            ht = item;
                            var insStu = new MODEL.Ali.EditAli_Orders();

                            #region Init Stu

                            insStu.BizID_VALUE = ht["bizId"];
                            insStu.ORDERID_VALUE = orderID; //ht["orderId"];
                            insStu.ORDERDATE_VALUE = ht["orderDate"];
                            insStu.ENIDVALUE = ht["snapshotId"];

                            //if (string.IsNullOrEmpty(insStu.ENIDVALUE.ToString()))
                            //{
                            //    sb.Append("根据订单号：" + orderID + "获取订单信息中snapshotId为空！\r\n");
                            //}

                            insStu.PRODUCTNAME_VALUE = ht["productName"];
                            insStu.PRODUCTSKUINFO_VALUE = ht["skuInfo"];
                            insStu.PRODUCTSNAPSHOTURL_VALUE = ht["productSnapshotUrl"];
                            insStu.PRODUCTPROPERTIES_VALUE = ht["productProperties"];
                            insStu.PRODUCTTYPE_VALUE = ht["productLeafCategoryId"];
                            insStu.ORDERFROMTYPE_VALUE = (int)OrderFromType.Aliexpress;
                            if (ht["warrantyInForceStatus"] != null)
                            {
                                if (ht["warrantyInForceStatus"].ToString() == "enabled")
                                    insStu.EFFECTIVE_VALUE = true;
                                var warrantyHt = ht["warrantyInfo"] as Hashtable;
                                if (warrantyHt != null && warrantyHt["judgeInforceTime"] != null)
                                {
                                    insStu.EFFECTIVEDATE_VALUE = warrantyHt["judgeInforceTime"];
                                }
                                else
                                {
                                    insStu.EFFECTIVEDATE_VALUE = ht["judgeInforceTime"];
                                }
                            }
                            var orderHt = ht["orderInfo"] as Hashtable;
                            if (orderHt != null)
                            {
                                if (orderHt["sellerAliId"] != null)
                                {
                                    insStu.SELLERALIID_VALUE = orderHt["sellerAliId"];
                                }
                                if (orderHt["buyerAliId"] != null)
                                {
                                    insStu.BUYERALIID_VALUE = orderHt["buyerAliId"];
                                }
                            }

                            if (ht["productProperties"] != null &&
                                !string.IsNullOrEmpty(ht["productProperties"].ToString()))
                            {
                                try
                                {
                                    #region Propertites

                                    var jsonData =
                                        JSON.Decode(ht["productProperties"].ToString()) as Hashtable;
                                    insStu.BRANDNAMEVALUE = jsonData["Brand Name"];
                                    insStu.PRODUCTMODELVALUE = jsonData["Model"];
                                    if (string.IsNullOrEmpty(insStu.PRODUCTMODELVALUE.ToString()))
                                    {
                                        foreach (var key in jsonData.Keys)
                                        {
                                            if ((key.ToString().ToLower().EndsWith("model") ||
                                                 key.ToString().Trim().ToLower() == "model" ||
                                                 key.ToString().Trim().ToLower() == "model number")
                                                && jsonData[key] != null
                                                && !string.IsNullOrEmpty(jsonData[key].ToString()))
                                            {
                                                insStu.PRODUCTMODELVALUE = jsonData[key];
                                            }
                                        }
                                    }
                                    insStu.ITEMCONDITIONVALUE = jsonData["Item Condition"];
                                    insStu.RAMVALUE = jsonData["RAM"];
                                    insStu.ROMVALUE = jsonData["ROM"];
                                    insStu.DISPLAYSIZEVALUE = jsonData["Display Size"];
                                    insStu.DISPLAYRESOLUTIONVALUE = jsonData["Display Resolution"];
                                    insStu.BATTERYCAPACITYVALUE = jsonData["Battery Capacity(mAh)"];
                                    insStu.CPUVALUE = jsonData["CPU"];
                                    insStu.SIZEVALUE = jsonData["Size"];
                                    insStu.OPERATIONSYSTEMVALUE = jsonData["Operation System"];
                                    insStu.OSVALUE = jsonData["OS"];

                                    #endregion
                                }
                                catch
                                {
                                }
                            }

                            insStu.STOREURL_VALUE = ht["storeUrl"];

                            //if (dt.Columns.Contains("register_country_id"))
                            //{
                            //    insStu.SELLERCOUNTRY_VALUE = dr["register_country_id"];
                            //}
                            //if (dt.Columns.Contains("register_province_name"))
                            //{
                            //    insStu.SELLERPROVINCE_VALUE = dr["register_province_name"];
                            //}
                            //if (dt.Columns.Contains("full_name"))
                            //{
                            //    insStu.SELLERNAME_VALUE = dr["full_name"];
                            //}
                            //if (dt.Columns.Contains("email"))
                            //{
                            //    insStu.SELLEREMAIL_VALUE = dr["email"];
                            //}
                            //买家国家
                            if (ht["country"] != null && !string.IsNullOrEmpty(ht["country"].ToString()))
                            {
                                insStu.COUNTRY_VALUE = ht["country"];
                            }
                            else
                            {
                                //insStu.COUNTRY_VALUE = dt.Columns.Contains("buyer_country_id")
                                //    ? dr["buyer_country_id"].ToString()
                                //    : string.Empty;
                            }
                            //买家省份
                            if (ht["province"] != null &&
                                !string.IsNullOrEmpty(ht["province"].ToString()))
                            {
                                insStu.PROVINCE_VALUE = ht["province"];
                            }
                            else
                            {
                                //insStu.PROVINCE_VALUE = dt.Columns.Contains("buyer_province")
                                //    ? dr["buyer_province"].ToString()
                                //    : string.Empty;
                            }
                            //买家城市
                            if (ht["city"] != null && !string.IsNullOrEmpty(ht["city"].ToString()))
                            {
                                insStu.CITY_VALUE = ht["city"];
                            }
                            else
                            {
                                //insStu.CITY_VALUE = dt.Columns.Contains("buyer_city")
                                //    ? dr["buyer_city"].ToString()
                                //    : string.Empty;
                            }

                            insStu.STREETADDRESS_VALUE = ht["streetAddress"]; //买家街道
                            insStu.POSTCODE_VALUE = ht["postCode"]; //买家邮编
                            insStu.SENDGOODSTIME_VALUE = ht["sendGoodsTime"]; //产品发货时间
                            insStu.SELLERIDGETGOODSTIME_VALUE = ht["getGoodsTime"]; //产品收货时间
                            insStu.PRODUCTCOUNT_VALUE = ht["productCount"]; //产品数量
                            insStu.STATUS_VALUE = ht["status"];
                            //交易状态。订单状态： 1.PLACE_ORDER_SUCCESS（下单成功）2.WAIT_SELLER_SEND_GOODS（待卖家发货）3.SELLER_PART_SEND_GOODS（待卖家部分发货）4.WAIT_BUYER_ACCEPT_GOODS（等待买家收货）5.FUND_PROCESSING（资金处理中）6.FINISH（交易成功）
                            insStu.PRODUCTAMOUNT_VALUE = ht["productAmount"]; //产品金额，分
                            insStu.SERVICEAMOUNT_VALUE = ht["serviceAmount"]; //保修金额，分
                            insStu.PAYCURRENCY_VALUE = ht["payCurrency"]; //支付币种
                            insStu.ORDERCURRENCY_VALUE = ht["orderCurrency"]; //订单币种
                            insStu.EXCHANGE_VALUE = ht["exchange"]; //汇率
                            insStu.WARRANTYTYPE_VALUE = ht["warrantyType"];
                            //保修类型. 1.warranty_common（普通保修）2.warranty_refund（只退不修）
                            insStu.SERVICESTARTTIME_VALUE = ht["serviceStartTime"]; //服务开始时间，买家确认收货之前为空
                            insStu.SERVICEENDTIME_VALUE = ht["serviceEndTime"]; //服务结束时间，买家确认收货之前为空
                            insStu.WARRANTYSTATUS_VALUE = ht["warrantyStatus"];
                            //保修状态 1.notSubmit(未提交)2.create（创建）3.cancel（取消）4.finish（完成）
                            insStu.NAME_VALUE = ht["name"]; //买家姓名,warrantyStatus=notSubmit时为空
                            insStu.TELEPHONE_VALUE = ht["telephone"]; //买家电话,warrantyStatus=notSubmit时为空
                            insStu.DESCRIPTION_VALUE = ht["description"];
                            //买家保修描述,warrantyStatus=notSubmit时为空
                            insStu.ATTACHMENTS_VALUE = ht["attachments"];
                            //买家保修提交附件，逗号分隔,warrantyStatus=notSubmit时为空

                            #endregion

                            //if (effDateFlag && ht["bizId"] != null && ht["bizId"].ToString() == bizId)
                            //{
                            //    insStu.EFFECTIVE_VALUE = true;
                            //    insStu.EFFECTIVEDATE_VALUE = effectiveDate;
                            //}

                            insStu.ACTION_VALUE = "Insert";

                            int res = serv.EditAli_Orders(ref insStu);
                            if (res > 0)
                            {
                                addSuccessCount++;
                            }
                            else
                            {
                                addFaildCount++;
                                sb.Append("新增失败！OrderID：" + orderID + "；Enid：" + ht["snapshotId"] + "\r\n");
                            }
                        }
                    }
                }
                else
                {
                    sb.Append("根据订单号：" + orderID + "获取订单信息失败！" + htFirst["msg"] + "\r\n");
                }

                #endregion
            }
            else
            {
                for (var i = 0; i < oDt.Rows.Count; i++)
                {
                    //更新 部分字段
                    var dr = oDt.Rows[i];
                    try
                    {
                        var id = dr["ID"].ToString();
                        var enid = dr["ENid"].ToString();
                        var bzId = dr["bizId"].ToString();
                        var entity = new MODEL.Ali.EditAli_Orders
                        {
                            ACTION_VALUE = "Update",
                            ID_VALUE = id
                        };


                        var resJson = aliApiServ.GetOrderInfo(dr["OrderId"].ToString(),false,false);

                        var htFirst = JSON.Decode(resJson) as Hashtable;
                        if (htFirst["success"].ToString().ToLower() == "true")
                        {

                            var arrayList = htFirst["dataList"] as ArrayList;
                            if (arrayList != null)
                            {

                                var ht = new Hashtable();
                                foreach (
                                    Hashtable item in
                                        arrayList.Cast<Hashtable>()
                                            .Where(
                                                item =>
                                                    item["bizId"].ToString() == bzId))
                                {
                                    ht = item;
                                }
                                if (ht.Count <= 0)
                                {
                                    sb.Append("调用Ali接口数据中没有Order=" +
                                              orderID + ";bizId=" +
                                              bzId + ";\r\n");
                                }

                                #region Init  只同步部分数据
                                var orderHt = ht["orderInfo"] as Hashtable;
                                if (orderHt != null)
                                {
                                    if (orderHt["sellerAliId"] != null)
                                    {
                                        entity.SELLERALIID_VALUE = orderHt["sellerAliId"];
                                    }
                                    if (orderHt["buyerAliId"] != null)
                                    {
                                        entity.BUYERALIID_VALUE = orderHt["buyerAliId"];
                                    }
                                }
                                entity.PRODUCTTYPE_VALUE = ht["productLeafCategoryId"];
                                if (ht["warrantyInForceStatus"] != null)
                                {
                                    if (ht["warrantyInForceStatus"].ToString() == "enabled")
                                        entity.EFFECTIVE_VALUE = true;
                                    var warrantyHt = ht["warrantyInfo"] as Hashtable;
                                    if (warrantyHt != null && warrantyHt["judgeInforceTime"] != null)
                                    {
                                        entity.EFFECTIVEDATE_VALUE = warrantyHt["judgeInforceTime"];
                                    }
                                    else
                                    {
                                        entity.EFFECTIVEDATE_VALUE = ht["judgeInforceTime"];
                                    }
                                }
                                //买家国家
                                if (ht["country"] != null &&
                                    !string.IsNullOrEmpty(ht["country"].ToString()))
                                {
                                    entity.COUNTRY_VALUE = ht["country"];
                                }
                                //买家省份
                                if (ht["province"] != null &&
                                    !string.IsNullOrEmpty(ht["province"].ToString()))
                                {
                                    entity.PROVINCE_VALUE = ht["province"];
                                }
                                //买家城市
                                if (ht["city"] != null &&
                                    !string.IsNullOrEmpty(ht["city"].ToString()))
                                {
                                    entity.CITY_VALUE = ht["city"];
                                }

                                entity.STREETADDRESS_VALUE = ht["streetAddress"]; //买家街道
                                entity.POSTCODE_VALUE = ht["postCode"]; //买家邮编
                                entity.SENDGOODSTIME_VALUE = ht["sendGoodsTime"]; //产品发货时间
                                entity.SELLERIDGETGOODSTIME_VALUE = ht["getGoodsTime"]; //产品收货时间
                                //entity.PRODUCTCOUNT_VALUE = ht["productCount"]; //产品数量
                                entity.STATUS_VALUE = ht["status"];
                                //交易状态。订单状态： 1.PLACE_ORDER_SUCCESS（下单成功）2.WAIT_SELLER_SEND_GOODS（待卖家发货）3.SELLER_PART_SEND_GOODS（待卖家部分发货）4.WAIT_BUYER_ACCEPT_GOODS（等待买家收货）5.FUND_PROCESSING（资金处理中）6.FINISH（交易成功）
                                entity.WARRANTYTYPE_VALUE = ht["warrantyType"];
                                //保修类型. 1.warranty_common（普通保修）2.warranty_refund（只退不修）
                                entity.SERVICESTARTTIME_VALUE = ht["serviceStartTime"];
                                //服务开始时间，买家确认收货之前为空
                                entity.SERVICEENDTIME_VALUE = ht["serviceEndTime"];
                                //服务结束时间，买家确认收货之前为空
                                entity.WARRANTYSTATUS_VALUE = ht["warrantyStatus"];
                                //保修状态 1.notSubmit(未提交)2.create（创建）3.cancel（取消）4.finish（完成）
                                entity.NAME_VALUE = ht["name"]; //买家姓名,warrantyStatus=notSubmit时为空
                                entity.TELEPHONE_VALUE = ht["telephone"];
                                //买家电话,warrantyStatus=notSubmit时为空
                                entity.DESCRIPTION_VALUE = ht["description"];
                                //买家保修描述,warrantyStatus=notSubmit时为空
                                entity.ATTACHMENTS_VALUE = ht["attachments"];
                                //买家保修提交附件，逗号分隔,warrantyStatus=notSubmit时为空

                                #endregion

                                //if (effDateFlag)
                                //{
                                //    entity.EFFECTIVE_VALUE = true;
                                //    entity.EFFECTIVEDATE_VALUE = effectiveDate;
                                //}
                            }

                            if (serv.EditAli_Orders(ref entity) > 0)
                            {
                                updateSuccessCount++;
                            }
                            else
                            {
                                updateFaildCount++;
                            }
                        }
                        else
                        {
                            sb.Append("调用Ali接口失败;OrderId" + orderID + "|" + htFirst["msg"] + "\r\n");
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append("异常：" + ex.Message + "|Order:" + orderID);
                    }
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 根据Hashtable 绑定对象
        /// </summary>
        /// <param name="htFirst"></param>
        /// <param name="bizId"></param>
        /// <param name="isAll"></param>
        /// <param name="entity"></param>
        public static void InitDataEntity(Hashtable htFirst, string bizId, bool isAll, ref MODEL.Ali.EditAli_Orders entity)
        {
            var arrayList = htFirst["dataList"] as ArrayList;
            if (arrayList != null)
            {

                var ht = new Hashtable();

                //foreach (
                //    Hashtable item in
                //        arrayList.Cast<Hashtable>()
                //            .Where(
                //                item =>
                //                    item["productSnapshotUrl"].ToString()
                //                        .Contains("/" + enIdArr[i] + ".html")))
                //{
                //    ht = item;
                //}
                //if (string.IsNullOrEmpty(bizId) && arrayList.Count == 1)
                //{
                //    //处理Enid 为null 且一个订单号只有一个子订单
                //    var hashTable = arrayList[0] as Hashtable;
                //    bizId = hashTable != null && hashTable["bizId"] != null
                //        ? hashTable["bizId"].ToString()
                //        : "";
                //    entity.ENIDVALUE = enID;
                //}
                //if (string.IsNullOrEmpty(enID))
                //{
                //    ht = arrayList[0] as Hashtable;
                //}
                //else
                //{
                    foreach (
                        Hashtable item in
                            arrayList.Cast<Hashtable>()
                                .Where(
                                    item =>
                                        item["bizId"].ToString() == bizId))
                    {
                        ht = item;
                    }
                //}



                //insStu.ORDERID_VALUE = ht["orderId"];
                entity.BizID_VALUE = ht["bizId"];
                entity.ORDERDATE_VALUE = ht["orderDate"];
                entity.PRODUCTNAME_VALUE = ht["productName"];
                entity.PRODUCTSKUINFO_VALUE = ht["skuInfo"];
                entity.PRODUCTSNAPSHOTURL_VALUE = ht["productSnapshotUrl"];
                entity.PRODUCTPROPERTIES_VALUE = ht["productProperties"];
                entity.PRODUCTTYPE_VALUE = ht["productLeafCategoryId"];
                entity.ORDERFROMTYPE_VALUE = (int) OrderFromType.Aliexpress;
                var orderHt = ht["orderInfo"] as Hashtable;
                if (orderHt != null)
                {
                    if (orderHt["sellerAliId"] != null)
                    {
                        entity.SELLERALIID_VALUE = orderHt["sellerAliId"];
                    }
                    if (orderHt["buyerAliId"] != null)
                    {
                        entity.BUYERALIID_VALUE = orderHt["buyerAliId"];
                    }
                }
                if (ht["warrantyInForceStatus"] != null)
                {
                    if (ht["warrantyInForceStatus"].ToString() == "enabled")
                        entity.EFFECTIVE_VALUE = true;
                    var warrantyHt = ht["warrantyInfo"] as Hashtable;
                    if (warrantyHt != null && warrantyHt["judgeInforceTime"] != null)
                    {
                        entity.EFFECTIVEDATE_VALUE = warrantyHt["judgeInforceTime"];
                    }
                    else
                    {
                        entity.EFFECTIVEDATE_VALUE = ht["judgeInforceTime"];
                    }
                }

                if (isAll)
                {
                    if (ht["productProperties"] != null &&
                        !string.IsNullOrEmpty(ht["productProperties"].ToString()))
                    {
                        try
                        {
                            var jsonData = JSON.Decode(ht["productProperties"].ToString()) as Hashtable;
                            if (jsonData != null)
                            {
                                entity.BRANDNAMEVALUE = jsonData["Brand Name"];
                                entity.PRODUCTMODELVALUE = jsonData["Model"];
                                if (string.IsNullOrEmpty(entity.PRODUCTMODELVALUE.ToString()))
                                {
                                    foreach (var key in jsonData.Keys)
                                    {
                                        if ((key.ToString().ToLower().EndsWith("model") ||
                                             key.ToString().Trim().ToLower() == "model" ||
                                             key.ToString().Trim().ToLower() == "model number")
                                            && jsonData[key] != null
                                            && !string.IsNullOrEmpty(jsonData[key].ToString()))
                                        {
                                            entity.PRODUCTMODELVALUE = jsonData[key];
                                        }
                                    }
                                }
                                //手机
                                if ( entity.PRODUCTTYPE_VALUE.ToString() ==
                                    (((int) ProductType.Phone).ToString(CultureInfo.InvariantCulture)))
                                {
                                    entity.ITEMCONDITIONVALUE = jsonData["Item Condition"];
                                    entity.RAMVALUE = jsonData["RAM"];
                                    entity.ROMVALUE = jsonData["ROM"];
                                    entity.DISPLAYSIZEVALUE = jsonData["Display Size"];
                                    entity.DISPLAYRESOLUTIONVALUE = jsonData["Display Resolution"];
                                    entity.BATTERYCAPACITYVALUE = jsonData["Battery Capacity(mAh)"];
                                    entity.CPUVALUE = jsonData["CPU"];
                                    entity.SIZEVALUE = jsonData["Size"];
                                    entity.OPERATIONSYSTEMVALUE = jsonData["Operation System"];
                                    entity.OSVALUE = jsonData["OS"];
                                }
                                else if (entity.PRODUCTTYPE_VALUE.ToString() ==
                                         (((int) ProductType.TabletPC).ToString(CultureInfo.InvariantCulture)))
                                {
                                    //平板
                                    entity.ITEMCONDITIONVALUE = jsonData["Status"];
                                    entity.RAMVALUE = jsonData["Memory Capacity"];
                                    entity.ROMVALUE = jsonData["Tablet Data Capacity"];
                                    entity.DISPLAYSIZEVALUE = jsonData["Screen Size"];
                                    entity.DISPLAYRESOLUTIONVALUE = jsonData["Display Resolution"];
                                    if (string.IsNullOrEmpty(entity.DISPLAYRESOLUTIONVALUE.ToString()))
                                    {
                                        entity.DISPLAYRESOLUTIONVALUE = jsonData["Display resolution"];
                                    }
                                    entity.BATTERYCAPACITYVALUE = jsonData["Cell Capacity"];
                                    entity.CPUVALUE = jsonData["Processor Manufacture"];
                                    //entity.SIZEVALUE = jsonData["Screen Size"];
                                    entity.OPERATIONSYSTEMVALUE = jsonData["Operation System"];
                                    if (string.IsNullOrEmpty(entity.OPERATIONSYSTEMVALUE.ToString()))
                                    {
                                        entity.OPERATIONSYSTEMVALUE = jsonData["Operating System"];
                                    }
                                    //entity.OSVALUE = jsonData["OS"];
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }

                entity.STOREURL_VALUE = ht["storeUrl"];
                //买家国家
                if (ht["country"] != null && !string.IsNullOrEmpty(ht["country"].ToString()))
                {
                    entity.COUNTRY_VALUE = ht["country"];
                }
                //买家省份
                if (ht["province"] != null && !string.IsNullOrEmpty(ht["province"].ToString()))
                {
                    entity.PROVINCE_VALUE = ht["province"];
                }
                //买家城市
                if (ht["city"] != null && !string.IsNullOrEmpty(ht["city"].ToString()))
                {
                    entity.CITY_VALUE = ht["city"];
                }

                entity.STREETADDRESS_VALUE = ht["streetAddress"]; //买家街道
                entity.POSTCODE_VALUE = ht["postCode"]; //买家邮编
                entity.SENDGOODSTIME_VALUE = ht["sendGoodsTime"]; //产品发货时间
                entity.SELLERIDGETGOODSTIME_VALUE = ht["getGoodsTime"]; //产品收货时间
                entity.PRODUCTCOUNT_VALUE = ht["productCount"]; //产品数量
                entity.STATUS_VALUE = ht["status"];
                //交易状态。订单状态： 1.PLACE_ORDER_SUCCESS（下单成功）2.WAIT_SELLER_SEND_GOODS（待卖家发货）3.SELLER_PART_SEND_GOODS（待卖家部分发货）4.WAIT_BUYER_ACCEPT_GOODS（等待买家收货）5.FUND_PROCESSING（资金处理中）6.FINISH（交易成功）
                entity.PRODUCTAMOUNT_VALUE = ht["productAmount"]; //产品金额，分
                entity.SERVICEAMOUNT_VALUE = ht["serviceAmount"]; //保修金额，分
                entity.PAYCURRENCY_VALUE = ht["payCurrency"]; //支付币种
                entity.ORDERCURRENCY_VALUE = ht["orderCurrency"]; //订单币种
                entity.EXCHANGE_VALUE = ht["exchange"]; //汇率
                entity.WARRANTYTYPE_VALUE = ht["warrantyType"];
                //保修类型. 1.warranty_common（普通保修）2.warranty_refund（只退不修）
                entity.SERVICESTARTTIME_VALUE = ht["serviceStartTime"]; //服务开始时间，买家确认收货之前为空
                entity.SERVICEENDTIME_VALUE = ht["serviceEndTime"]; //服务结束时间，买家确认收货之前为空
                entity.WARRANTYSTATUS_VALUE = ht["warrantyStatus"];
                //保修状态 1.notSubmit(未提交)2.create（创建）3.cancel（取消）4.finish（完成）
                entity.NAME_VALUE = ht["name"]; //买家姓名,warrantyStatus=notSubmit时为空
                entity.TELEPHONE_VALUE = ht["telephone"]; //买家电话,warrantyStatus=notSubmit时为空
                entity.DESCRIPTION_VALUE = ht["description"]; //买家保修描述,warrantyStatus=notSubmit时为空
                entity.ATTACHMENTS_VALUE = ht["attachments"];
                //买家保修提交附件，逗号分隔,warrantyStatus=notSubmit时为空
            }
        }

        /// <summary>
        /// 根据起始时间，结束时间，同步订单信息，不存在则新增，存在则同步部分信息
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="total"></param>
        /// <param name="addSuccCount"></param>
        /// <param name="addFaildCount"></param>
        /// <param name="updateSuccCount"></param>
        /// <param name="updateFaildCount"></param>
        public static string GetOrderList(DateTime startDate, DateTime endDate, out int total, out int addSuccCount, out int addFaildCount, out int updateSuccCount, out int updateFaildCount)
        {
            total = addSuccCount = addFaildCount = updateSuccCount = updateFaildCount = 0;
            var resJson = new RunAliAPI().GetOrderList(startDate.ToString("yyyy-MM-dd") + " 00:00:00",
                endDate.ToString("yyyy-MM-dd") + " 00:00:00", 200, 1, false, false);

            var htFirst = JSON.Decode(resJson) as Hashtable;

            var sb = new StringBuilder();

            if (htFirst["success"].ToString().ToLower() == "true")
            {
                total = int.Parse(htFirst["totalItem"].ToString());

                int pageIndex = 1;
                int count1 = 0;
                int count2 = 0;
                int count3 = 0;
                int count4 = 0;
                sb.Append(
                    SyncOrderInfo(startDate, endDate, 200, 1, out total, out count1, out count2, out count3, out count4) +
                    "\r\n");
                addSuccCount += count1;
                addFaildCount += count2;
                updateSuccCount += count3;
                updateFaildCount += count4;
                do
                {
                    pageIndex = pageIndex + 1;

                    int c1 = 0;
                    int c2 = 0;
                    int c3 = 0;
                    int c4 = 0;
                    sb.Append(
                        SyncOrderInfo(startDate, endDate, 200, pageIndex, out total, out c1, out c2, out c3, out c4) +
                        "\r\n");
                    addSuccCount += c1;
                    addFaildCount += c2;
                    updateSuccCount += c3;
                    updateFaildCount += c4;

                } while (pageIndex*200 < total);
            }
            else
            {
                sb.AppendFormat("调用接口GetOrderList失败！StartDate:{0},EndDate:{1}PageSize:{2},PageIndex:{3}\r\n",
                    startDate, endDate, 200, 1);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 根据起始时间，结束时间，pageSize,pageIndex同步订单信息 ，不存在则新增，存在则同步部分信息
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="total"></param>
        /// <param name="addSuccCount"></param>
        /// <param name="addFaildCount"></param>
        /// <param name="updateSuccCount"></param>
        /// <param name="updateFaildCount"></param>
        /// <returns></returns>
        public static string SyncOrderInfo(DateTime startDate, DateTime endDate,int pageSize,int pageIndex, out int total, out int addSuccCount,
            out int addFaildCount, out int updateSuccCount, out int updateFaildCount)
        {
            total = addSuccCount = addFaildCount = updateSuccCount = updateFaildCount = 0;
            var resJson = new RunAliAPI().GetOrderList(startDate.ToString("yyyy-MM-dd") + " 00:00:00",
                endDate.ToString("yyyy-MM-dd") + " 00:00:00", pageSize, pageIndex, false, false);

            var htFirst = JSON.Decode(resJson) as Hashtable;

            var sb = new StringBuilder();

            if (htFirst["success"].ToString().ToLower() == "true")
            {
                total = int.Parse(htFirst["totalItem"].ToString());

                var arrayList = htFirst["dataList"] as ArrayList;
                if (arrayList != null)
                {
                    foreach (Hashtable item in arrayList.Cast<Hashtable>())
                    {
                        if (item["orderId"] == null || string.IsNullOrEmpty(item["orderId"].ToString())) continue;
                        int count1;
                        int count2;
                        int count3;
                        int count4;

                        var res = SyncOrderInfo(item["orderId"].ToString(), out count1, out count2, out count3,
                            out count4);
                        if (!string.IsNullOrEmpty(res))
                        {
                            sb.Append(res + "\r\n");
                        }
                        
                        addSuccCount += count1;
                        addFaildCount += count2;
                        updateSuccCount += count3;
                        updateFaildCount += count4;
                    }
                }
            }
            else
            {
                sb.AppendFormat("调用接口GetOrderList失败！StartDate:{0},EndDate:{1}PageSize:{2},PageIndex:{3}\r\n",
                    startDate, endDate, pageSize, pageIndex);
            }

            return sb.ToString();
        }
        /// <summary>
        /// 根据订单号调用接口，同步信息 不存在则新增，存在则同步部分信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="addSuccCount"></param>
        /// <param name="addFaildCount"></param>
        /// <param name="updateSuccCount"></param>
        /// <param name="updateFaildCount"></param>
        /// <returns></returns>
        public static string SyncOrderInfo(string orderId,out int addSuccCount, out int addFaildCount, out int updateSuccCount, out int updateFaildCount)
        {

            addSuccCount = addFaildCount = updateSuccCount = updateFaildCount = 0;
            var sbFail = new StringBuilder();
            try
            {

                var serv = new Ali_OrdersB();
                var aliApiServ = new RunAliAPI();

                //根据订单号和ENid判断是否存在
                var stu = new MODEL.Ali.GetAli_Orders {ORDERIDVALUE = orderId};
                var oDt = serv.GetAli_Orders(ref stu);

                if (oDt == null || oDt.Rows.Count <= 0)
                {
                    //订单不存在， 新增
                    var resJson = aliApiServ.GetOrderInfo(orderId, false, false);

                    var htFirst = JSON.Decode(resJson) as Hashtable;
                    if (htFirst["success"].ToString().ToLower() == "true")
                    {
                        var arrayList = htFirst["dataList"] as ArrayList;
                        if (arrayList != null)
                        {
                            foreach (Hashtable item in arrayList)
                            {
                                var insStu = new MODEL.Ali.EditAli_Orders();
                                insStu.ORDERID_VALUE = orderId;
                                insStu.BizID_VALUE = item["bizId"];
                                insStu.ENIDVALUE = item["snapshotId"];
                                //insStu.RUIDVALUE = ruid;

                                InitDataEntity(htFirst, insStu.BizID_VALUE.ToString(), true,
                                    ref insStu);

                                insStu.EFFECTIVE_VALUE = false;
                                insStu.ACTION_VALUE = "Insert";
                                insStu.EFFECTIVE_VALUE = false;

                                int i = serv.EditAli_Orders(ref insStu);
                                if (i > 0)
                                    addSuccCount++;
                                else
                                {
                                    addFaildCount++;
                                }
                            }
                        }
                    }
                    else
                    {
                        sbFail.Append("根据订单号：" + orderId + "获取订单信息失败！\r\n");
                    }
                }
                else
                {
                    //订单存在   同步部分信息
                    foreach (DataRow dr in oDt.Rows)
                    {
                        var entity = new MODEL.Ali.EditAli_Orders
                        {
                            ACTION_VALUE = "Update",
                            ID_VALUE = dr["ID"].ToString()
                        };

                        var resJson = aliApiServ.GetOrderInfo(dr["OrderId"].ToString(), false, false);


                        var htFirst = JSON.Decode(resJson) as Hashtable;
                        if (htFirst["success"].ToString().ToLower() == "true")
                        {

                            InitDataEntity(htFirst, dr["BizID"].ToString(),
                                false, ref entity);

                            int i = serv.EditAli_Orders(ref entity);
                            if (i > 0)
                                updateSuccCount++;
                            else
                            {
                                updateFaildCount++;
                            }
                        }
                        else
                        {
                            sbFail.Append("根据订单号：" + orderId + "获取订单信息失败！\r\n");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                sbFail.Append("异常：" + ex.Message + ex.StackTrace);
            }
            return sbFail.ToString();
        }
    }
}